package cn.echcz.register

import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

import scala.collection.mutable
import scala.concurrent.duration._

/**
  * 服务提供者
  * @param id 服务id
  * @param health 服务健康值
  * @param rHost 注册中心地址
  * @param rPort 注册中心端口
  */
class Client(val host: String, val port: String, rHost: String, rPort: String) extends Actor {
  // 设置心跳发送间隔为10秒
  val HEARTBEAT_INTERVAL = 10000
  var rSelection: ActorSelection = _
  val REGISTER_SUCCESS = "register_success"
  val HEARTBEAT = "heartbeat"

  // 初始化
  override def preStart(): Unit = {
    // 获取注册中心的actor
    rSelection = context.actorSelection(s"akka.tcp://registerActorSystem@$rHost:$rPort/user/registerActor")
    // 向注册中心发送注册信息
    rSelection ! ClientInfo(host, port)
  }

  override def receive: Receive = {
    case REGISTER_SUCCESS => {
      println(s"${host}:${port}注册成功")
      // 定期向自己发送心跳信息
      import context.dispatcher
      context.system.scheduler.schedule(0 millis, HEARTBEAT_INTERVAL millis, self, HEARTBEAT)
    }
    // 中转心跳信息
    case HEARTBEAT => {
      rSelection ! (HEARTBEAT, host, port)
    }
    // 如果收到注册中心发来的服务者列表...
    case s: mutable.TreeSet[ServerInfo] => {
      println(s"----${s.size}----")
      s.foreach(println _)
      println("----------------")
    }
  }
}

object Client{
  def apply(host: String, port: String, rHost: String, rPort: String): ActorRef = {
    // 设置actorSystem的配置
    val configSetting =
      s"""
         |akka.actor.provider = "akka.remote.RemoteActorRefProvider"
         |akka.remote.netty.tcp.hostname = "$host"
         |akka.remote.netty.tcp.port = "$port"
       """.stripMargin
    val config = ConfigFactory.parseString(configSetting)
    // 创建ActorSystem
    val clientActorSystem = ActorSystem("clientActorSystem", config)
    clientActorSystem.actorOf(Props(new Client(host, port, rHost, rPort)), "clientActor")
  }
}
